require(boot) 
require(ergm) 
require(sna) 
LOWESTLL=-1e8 # lowest allowed loglikelihood to avoid numerical instabilities
tol=1e-6 # for convergence checking
	#IS this a term that ensures the network actually converges and doesn't have degeneracy problems? 

if (START=="READ") # read in a network and extract ego-networks as x
  {
  N=net$gal$n 
  directed= FALSE
  Y<-as.matrix.network(net)
  ### find each ego-network; use K steps out from each node
  # use Y+t(Y) to jump backwards across links at the second step out
  Y2<-Y+t(Y)
  net2<-network(Y2) #network object based upon the network matrix y which takes y and transforms it by	causing nodes to "jump backwards across links at the second step"
  x<-gapply(net2,c(1,2),1:N,"*",1,distance=K) 
  	#This abov line returns a vector obtained by applying a function to vertex neighborhoods ina  certain order. Here, this has the net2 object as the input graph, the margin of x to be used in calculating the network so that it is includin both rows and columns (total) = that's the second object in this function.  This does it for all nodes 1 through N, applying the star function with a maximum distance of K in which neighborhoods are taken.  
  	#The following for loop says for every node. apply a function over the list of vectors. I think this is just a way to change the matrix into a more readable x,y form
  for (i in 1:N)
    {
    x[[i]]<-c(i,x[[i]])
    x[[i]]<-as.matrix(Y[x[[i]],x[[i]]])
    }
  x<-lapply(x,network,directed=directed)
  rm(Y2,net2)
  
  # only look at egos bigger than MINSIZE.  Here I think the MINSIZE is however many connections they have
  if (MINSIZE>1)
    {
    keep<-lapply(x,network.size)>=MINSIZE
    all_net<-net
    N=all_net$gal$n
    net<-network(as.sociomatrix(all_net)[(1:N)[keep],(1:N)[keep]], directed = FALSE)
    for (att in list.vertex.attributes(all_net))
      set.vertex.attribute(net,att,get.vertex.attribute(all_net,att)[keep])
    rm(all_net)
    x<-x[keep]
    }
  N=length(x)
  }
if (START=="SIM")
  {
  #### simulate new data
  source("sim_networks_model.R")
  directed = FALSE
  x<-sim.x
  }
if (START=="RSIM")
  {
  #### read simulated data
  START="SIM"
  x<-sim.x
  N=length(x)
  }

